﻿using ExpertPdf.HtmlToPdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace RuiciWebSite.Common
{

    public class RuiciCommoms
    {
        public static string _sUploadImgPath = "/Styles/image/Upload/";
        //public static string _sImgPath = "http://img.bmyi.cn";
        public static string _sImgPath = System.Web.Configuration.WebConfigurationManager.AppSettings["ImageUrl"];
        private static readonly string myKey = "q0m3sd8l";
        public static List<string> doctorIdList = new List<string>();

        public loginInfo checkLoginStatus(HttpRequestBase request, HttpResponseBase response, HttpSessionStateBase Session)
        {
            loginInfo logInfo = new loginInfo();
            if (request.Cookies.Get("useridMsg") != null)
            {
                if (request.Cookies.Get("useridMsg").Values["userName"] != null)
                {
                    if (Session["userName"] != null && request.Cookies.Get("useridMsg").Values["userName"].ToString() != Session["userName"].ToString())
                    {
                        HttpCookie curCookie = request.Cookies.Get("useridMsg");
                        curCookie.Values["userName"] = Session["userName"].ToString();
                    }

                    HttpCookie cookie = request.Cookies.Get("useridMsg");
                    Session["userName"] = cookie.Values["userName"];
                    Session["isLogin"] = true;
                    Session["mobile"] = Decrypt(cookie.Values["mobile"], myKey);
                    Session["pid"] = Decrypt(cookie.Values["pid"], myKey);
                }
            }
            if (Session.Keys.Count != 0)
            {
                foreach (string key in Session.Keys)
                {
                    if (key.ToString() == "isLogin")
                        logInfo.isLogin = (bool)Session["isLogin"];

                    if (key.ToString() == "userName" && Session["userName"] != null)
                        logInfo.userName = Session["userName"].ToString();

                    if (key.ToString() == "mobile")
                        logInfo.mobile = Session["mobile"].ToString();

                    if (key.ToString() == "pid")
                        logInfo.picUrl = _sUploadImgPath + Session["pid"].ToString() + "Photo.jpg";
                }
            }
            else
            {
                logInfo.isLogin = false;
                logInfo.userName = string.Empty;
                logInfo.mobile = string.Empty;
            }
            return logInfo;
        }

        public loginInfo userLogout(HttpRequestBase request, HttpResponseBase response, HttpSessionStateBase Session)
        {
            loginInfo logInfo = new loginInfo();

            Session.RemoveAll();

            RemoveCookie(request, response);

            logInfo.isLogin = false;
            logInfo.userName = string.Empty;
            logInfo.mobile = string.Empty;

            return logInfo;
        }

        public void RemoveCookie(HttpRequestBase request, HttpResponseBase response)
        {
            HttpCookie CookieMsg = null;
            string cookieName;
            int iCookieCount = request.Cookies.Count;
            for (int i = 0; i < iCookieCount; i++)
            {
                cookieName = request.Cookies[i].Name;
                CookieMsg = new HttpCookie(cookieName);
                CookieMsg.Expires = DateTime.Now.AddDays(-1);
                response.Cookies.Add(CookieMsg);
            }
        }

        public string CheckValidateCode(HttpSessionStateBase Session, string sPhoneNumber, string sValidateCode)
        {
            string sErrorMessage = string.Empty;
            if ((Session["ValidationCode"] == null && Session["ValidationCodeGenerateTime"] == null && Session["ValidationPhone"] == null) ||
                (Session["ValidationCode"].ToString() == string.Empty && Session["ValidationCodeGenerateTime"].ToString() == string.Empty && Session["ValidationPhone"].ToString() == string.Empty))
            {
                sErrorMessage = "请先获取正确的手机验证码";
            }
            else
            {
                DateTime ValCodeGenTime = Convert.ToDateTime(Session["ValidationCodeGenerateTime"]);
                TimeSpan ts1 = new TimeSpan(ValCodeGenTime.Ticks);
                TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
                TimeSpan ts = ts1.Subtract(ts2).Duration();
                if (ts.Minutes <= 10)
                {
                    if (sPhoneNumber != Session["ValidationPhone"].ToString())
                        sErrorMessage = "请重新获取手机验证码";
                    else if (sValidateCode != Session["ValidationCode"].ToString())
                        sErrorMessage = "请输入正确的手机验证码";
                    else
                    {
                        Session["ValidationCode"] = string.Empty;
                        Session["ValidationCodeGenerateTime"] = string.Empty;
                        Session["ValidationPhone"] = string.Empty;
                    }
                }
                else
                    sErrorMessage = "手机验证码已过期";
            }

            return sErrorMessage;
        }

        public void GenerateValidateCode(HttpSessionStateBase Session, string sPhoneNumber)
        {
            Random ran = new Random();
            int RandKey = ran.Next(100000, 999999);
            Session["ValidationCode"] = RandKey;
            Session["ValidationCodeGenerateTime"] = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            Session["ValidationPhone"] = sPhoneNumber;
        }


        public string Use_ephtmltopdf(string HTMLContent, string outFile)
        {
            PdfConverter pdfConverter = new PdfConverter();
            pdfConverter.PdfDocumentOptions.EmbedFonts = false;
            pdfConverter.PdfDocumentOptions.ShowFooter = false;
            pdfConverter.PdfDocumentOptions.ShowHeader = false;
            pdfConverter.PdfDocumentOptions.GenerateSelectablePdf = true;
            pdfConverter.SavePdfFromHtmlStringToFile(HTMLContent, outFile);

            return outFile;
        }

        public void CreateCookie(HttpResponseBase response, string sUserName, string sMobile, int iPid)
        {
            HttpCookie cookie = new HttpCookie("useridMsg");
            cookie.Expires = DateTime.Now.AddDays(7);
            cookie["userName"] = sUserName;
            cookie["mobile"] = Encrypt(sMobile, myKey);
            cookie["pid"] = Encrypt(iPid.ToString(), myKey);
            response.Cookies.Add(cookie);
        }

        #region 加密方法
        /// <summary>
        /// 加密方法
        /// </summary>
        /// <param name="pToEncrypt">需要加密字符串</param>
        /// <param name="sKey">密钥</param>
        /// <returns>加密后的字符串</returns>
        public string Encrypt(string pToEncrypt, string sKey)
        {
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                //把字符串放到byte数组中


                //原来使用的UTF8编码，我改成Unicode编码了，不行
                byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);

                //建立加密对象的密钥和偏移量


                //使得输入密码必须输入英文文本
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                StringBuilder ret = new StringBuilder();
                foreach (byte b in ms.ToArray())
                {
                    ret.AppendFormat("{0:X2}", b);
                }
                ret.ToString();
                return ret.ToString();
            }
            catch (Exception ex)
            {

            }

            return "";
        }
        #endregion

        #region 解密方法
        /// <summary>
        /// 解密方法
        /// </summary>
        /// <param name="pToDecrypt">需要解密的字符串</param>
        /// <param name="sKey">密匙</param>
        /// <returns>解密后的字符串</returns>
        public string Decrypt(string pToDecrypt, string sKey)
        {
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
                for (int x = 0; x < pToDecrypt.Length / 2; x++)
                {
                    int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                    inputByteArray[x] = (byte)i;
                }

                //建立加密对象的密钥和偏移量，此值重要，不能修改
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                //建立StringBuild对象，CreateDecrypt使用的是流对象，必须把解密后的文本变成流对象
                StringBuilder ret = new StringBuilder();
                return System.Text.Encoding.Default.GetString(ms.ToArray());
            }
            catch (Exception ex)
            {

            }
            return "";
        }
        #endregion
    }

}

public class loginInfo
{
    public bool isLogin { get; set; }
    public string userName { get; set; }
    public string mobile { get; set; }
    public string picUrl { get; set; }
}
